!function namespace_prototype_extend() {
	// 格式化数字为 %[0-9]的字符串，不足前补0，超长前截去
	String.prototype.formatNumber = function(fmt){
		var m = fmt.match(/%(\d*)d/g);
		if(m.length < 1)
			throw new Error("unknown fomat:" + fmt);
		m = fmt.match(/\d*/g);
		var n = parseInt(m[1]);
		if(m[1] == "") n = 1;
		
		var s = n - this.length;
		if(s > 0 ){
			var str = "";
			for(var i=0; i<s; i++){
				str += "0";
			}
			return str+ this;
		} else if(s < 0){
			return this.substring(this.length - n);
		}
		return  this;
	};
	Number.prototype.formatNumber = function(fmt) {
		return (this + "").formatNumber(fmt);
	};
	
	Date.prototype.format = function(fmt){
		var year = this.getFullYear();
		var mont = this.getMonth() + 1;
		var days = this.getDate();
		var hour = this.getHours();
		var minu = this.getMinutes();
		var seco = this.getSeconds();
		var mill = this.getMilliseconds();
		
		var m = null;
		m = fmt.match(/y/g);	m =  m == null ? [] : m;	year = year.formatNumber("%" + m.length +"d");
		m = fmt.match(/M/g);	m =  m == null ? [] : m;	mont = mont.formatNumber("%" + m.length +"d");
		m = fmt.match(/d/g);	m =  m == null ? [] : m;	days = days.formatNumber("%" + m.length +"d");
		m = fmt.match(/H/g);	m =  m == null ? [] : m;	hour = hour.formatNumber("%" + m.length +"d");
		m = fmt.match(/m/g);	m =  m == null ? [] : m;	minu = minu.formatNumber("%" + m.length +"d");
		m = fmt.match(/s/g);	m =  m == null ? [] : m;	seco = seco.formatNumber("%" + m.length +"d");
		m = fmt.match(/S/g);	m =  m == null ? [] : m;	mill = mill.formatNumber("%" + m.length +"d");
		var str = fmt;
		str = str.replace(/y+/g, year);
		str = str.replace(/M+/g, mont);
		str = str.replace(/d+/g, days);
		str = str.replace(/H+/g, hour);
		str = str.replace(/m+/g, minu);
		str = str.replace(/s+/g, seco);
		str = str.replace(/S+/g, mill);
		
		return str;
	};
}();

!function namespace_login() {

	function LocalStorage () {
		if (window.localStorage) {
			this.get = function(key) {
				return window.localStorage.getItem(key);
			};

			this.set = function(key, value) {
				window.localStorage.setItem(key, value);
			};
			this.remove = function(key) {
				window.localStorage.removeItem(key);
			};
		} else {
			alert('注意：这个浏览器不是标准的Html5浏览器，请不要刷新页面，否则将会造成会话丢失');
			var storageInMemory = {};
			
			this.get = function(key) {
				return storageInMemory[key] || null;
			};
			this.set = function(key, value) {
				storageInMemory[key] = value;
			};
			this.remove = function(key) {
				delete storageInMemory[key];
			};
		}
	};
	
	function Security(store) {

		var __self = this;

		var __session = null;

		!function __setDefaultListeners() {
			// 本地还没有登录，弹出登录对话框
			$(__self).on('session.empty', function(event){
				// console.log(event);
			});
			// 
			$(__self).on('session.noop', function(event, session){
				// console.log(event);
			});
			
			// 调用时发现会话过期了，弹出登录对话框
			$(__self).on('session.expired', function(event, session){
				// console.log(event);
			});
			
			// 登录，初始化界面
			// 如果用户还是原来的用户，则界面依旧可以使用
			// 如用户已换，则销毁界面，重新初始化界面
			$(__self).on('session.logined', function(event, session, oldsession){
				// console.log(event);
			});
		}();
		
		this.loadLocalSession = function() {
			var session = store.get('USER_SESSION');
			if(null != session) {
				__session = JSON.parse(session);
			}
			return __session;
		};

		this.hasLocalSession = function() {
			return null != __session;
		};
		
		this.getLocalSession = function() {
			return __session;
		};
		this.getLocalSessionID = function() {
			return -1;
		};
		this.setLocalLoginTime = function(){
			store.set('LOGIN_TIME', new Date().getTime());
		};
		/**
		 * 仅提供给主页面登录成功后的本地会话更新
		 */
		this.setLocalSession = function(session) {
			var oldsession = __session;
			__session = session;
			$(this).trigger('session.logined', [session, oldsession]);
			store.set('USER_SESSION', JSON.stringify(session));
		};

		this.releaseLocalSession = function() {
			store.remove('USER_SESSION');
			__session = null;
		};
	}
	
	// 唯一实例
	window.Security = new Security(new LocalStorage());
//	window.Security.releaseLocalSession();
}();


!function namespace_proxy() {
	// 为了在Eclipse Outline中显示，特意定义为function
	function ResponseCode() {
		this.CLIENT_ERROR = -20000;
		this.SERVER_ERROR = -10000;
		this.SESSION_EXPIRED = -3;
		this.LOGIN_FAIL = -2;
		this.UNKNOWN = -1;
		this.SUCCESS = 1;
	};
	window.ResponseCode = new ResponseCode();
	
	function WaitHandler(success, failure) {
		this.handleSuccess = function(data) {
			if(data.code === window.ResponseCode.SESSION_EXPIRED) {
				$(window.Security).trigger('session.expired', [window.Security.getLocalSession()]);
			}
			
			if(data.code === window.ResponseCode.SUCCESS) {
				typeof(success) === 'function' && success(data);
				
			} else if('function' === typeof failure) {
				failure(data);
			} else {
				// NO-OP 调用方不关心失败
				// console.log(e);
			}
		};
		this.handleError = function(xhr, status, e) {
			if('function' === typeof failure) {
				failure({
					code: '-1000',
					message: '调用出现错误：' + e
				});
			} else {
				// NO-OP 调用方不关心失败
				// console.log(e);
			}
		};
	}
	
	function Proxy() {
		var __fn_default_headers = function() {
			return {
				SessionID: window.Security.getLocalSessionID()
			};
		};
		//
		// 请求响应码
		this.ResponseCode = window.ResponseCode;
		//
		this.login = function(userId, password, success, failure) {
			 
			$.ajax({
				url: 'rest/session/login',
				type: 'POST',
				dataType:"json",
				contentType:'application/json;charset=UTF-8',
				data: JSON.stringify({
					userID: userId,
					password: password
				}),
				success: new WaitHandler(success, failure).handleSuccess,
				error: new WaitHandler(success, failure).handleError
			});
		};
		this.noopSession = function(param, success, failure) {
			$.ajax({
				url: 'rest/session/noopSession',
				type: 'POST',
				dataType:"json",
				contentType: 'application/json;charset=UTF-8',
				headers: __fn_default_headers(),
				data: JSON.stringify(param),
				success: new WaitHandler(success, failure).handleSuccess,
				error: new WaitHandler(success, failure).handleError
			});
		};
		this.logoff = function(success, failure) {
			$.ajax({
				url: 'rest/session/logoff',
				type: 'GET',
				headers: __fn_default_headers(),
				success: new WaitHandler(success, failure).handleSuccess,
				error: new WaitHandler(success, failure).handleError
			});
		};
		this.getLoginUserId = function( )
		{
			 return window.Security.getLocalSession().user.userId ;
		};
		this.getLoginUser= function( )
		{
			 return window.Security.getLocalSession().user  ;
		};
		
		
		 
		this.generalPostAjax = function(endPoint,param, success, failure) {
			ajaxPostRequest(endPoint,param,false, success, failure);
		};
		this.generalPostAsyncAjax = function(endPoint,param, success, failure) {
			ajaxPostRequest(endPoint,param,true, success, failure);
		};
		var  ajaxPostRequest = function(endPoint,param,syn, success, failure) {
			$.ajax({
				url: endPoint,
				type: 'POST',
				dataType:"json",
				async:syn,
				contentType: 'application/json;charset=UTF-8',
				headers: __fn_default_headers(),
				data: JSON.stringify(param),
				success: new WaitHandler(success, failure).handleSuccess,
				error: new WaitHandler(success, failure).handleError
			});
		};
		
		
		
		this.generalGetAjax = function(endPoint,param, success, failure) {
			ajaxGetRequest(endPoint,param,false, success, failure);
		};
		this.generalGetAsyncAjax = function(endPoint,param, success, failure) {
			ajaxGetRequest(endPoint,param,true, success, failure);
		};
		var  ajaxGetRequest = function(endPoint,param,syn, success, failure) {
			$.ajax({
				url: endPoint,
				type: 'GET',
				dataType:"json",
				async:syn,
				contentType: 'application/json;charset=UTF-8',
				headers: __fn_default_headers(),
//				data: JSON.stringify(param),
				success: new WaitHandler(success, failure).handleSuccess,
				error: new WaitHandler(success, failure).handleError
			});
		};
		 
		
		
//		this.queryChannel = function(success, failure) {
//			alert('111-c1234');
//			$.ajax({
//				url: 'api/authorize/query',
//				type: 'POST',
//				async: false,
//				dataType:"json",
//				data: JSON.stringify({}),
//				contentType: 'application/json;charset=UTF-8',
//				// headers: {"Content-Type":"application/json"} , //__fn_default_headers(),
//				success: new WaitHandler(success, failure).handleSuccess,
//				error: new WaitHandler(success, failure).handleError
//			});
//		};
		
 
		
		
	}
	//=========================
	// 唯一实例！！！
	window.Proxy = new Proxy();
}();

